package fr.blogger.ejb.facade;

import java.io.IOException;

import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.github.slugify.Slugify;

import fr.blogger.ejb.model.Article;
import fr.blogger.ejb.model.Article_;

@Named
@Stateless
public class ArticleFacade extends AbstractFacade<Article> {

	@Override
	public Article update(Article article) {
		try {
			Slugify slugify = new Slugify(true);
			article.setSlug(slugify.slugify(article.getNom()));
			return super.update(article);
		} catch (IOException e) {
			// TODO : LOGGER
			e.printStackTrace();
			return article;
		}
	}

	@Override
	public Article create(Article article) {
		try {
			Slugify slugify = new Slugify(true);
			article.setSlug(slugify.slugify(article.getNom()));
			return super.create(article);
		} catch (IOException e) {
			// TODO : LOGGER
			e.printStackTrace();
			return article;
		}
	}

	public Article findBySlug(String slug) {
		CriteriaQuery query = initQuery();
		Root article = query.from(entityClass);
		Predicate cond1 = builder().equal(article.get(Article_.slug), slug);
		query.where(cond1);
		return (Article) em.createQuery(query).getSingleResult();
	}

}
